class_name ParticleIceMagic
extends GPUParticles2D

@export var auto_destroy_life_time: float = 1.5
@onready var animation_player: AnimationPlayer = $AnimationPlayer

@onready var hit_area: Area2D = $HitArea
@onready var collision_shape_2d: CollisionShape2D = $HitArea/CollisionShape2D
@export var hit_dot_interval: float = 1.0
var hit_dot_timer: float = 0
var hit_targets: Array = []

var sender: Node2D
var attack: float = 0
var critical_rate: float = 0
var critical_bonus: float = 0
var knockback: float = 0
var hit_cam_shake_intensity: float = 0
var hit_cam_shake_duration: float = 0
var level: Level = null

@onready var audio_ice: AudioStreamPlayer2D = $AudioIce


func _ready() -> void:
	restart()
	emitting = true
	animation_player.play("light")
	
	audio_ice.play()
	
	await get_tree().create_timer(auto_destroy_life_time).timeout
	queue_free()


func set_is_enemy(b: bool):
	hit_area.set_collision_mask_value(5, true)
	if b:
		hit_area.set_collision_mask_value(7, true)
		hit_area.set_collision_mask_value(6, false)
	else:
		hit_area.set_collision_mask_value(7, false)
		hit_area.set_collision_mask_value(6, true)


func _physics_process(delta: float) -> void:
	process_hit_cooldown(delta)
	process_hit()
	

func process_hit_cooldown(delta: float):
	if collision_shape_2d.disabled: return
	
	hit_dot_timer -= delta
	if hit_dot_timer <= 0:
		hit_dot_timer = hit_dot_interval
		hit_targets = []
		

func process_hit():
	if collision_shape_2d.disabled: return
	
	var areas = hit_area.get_overlapping_areas()
	if areas.size() <= 0: return
	
	for area in areas:
		var source = area.source
		if not source in hit_targets:
			hit_targets.append(source)
		
			var hit_data = get_hit_data()
			source.take_hit(hit_data, sender)
			level.camera.start_shake(hit_cam_shake_intensity, hit_cam_shake_duration)
	

func get_hit_data():
	var is_critical = randf() <= critical_rate
	var critical_attack = attack * (1.0 + critical_bonus)
	
	var hit_data = HitData.new()
	hit_data.is_critical = is_critical
	hit_data.attack = critical_attack if is_critical else attack
	hit_data.knockback = knockback
	
	return hit_data
		
